' Stephen Toub
' Coded and published in January 2007 issue of MSDN Magazine 
' http://msdn.microsoft.com/msdnmag/issues/07/01/PreviewHandlers/default.aspx


Imports Microsoft.VisualBasic
Imports System
Imports System.IO
Imports System.Windows.Forms
Imports System.Runtime.InteropServices
Imports System.Reflection
Imports System.Globalization
Imports C4F.DevKit.PreviewHandler.PreviewHandlerFramework

Namespace C4F.DevKit.PreviewHandler.PreviewHandlers
    <PreviewHandler("MSDN Magazine PDF Preview Handler", ".pdf", "{E1B9A916-BD9E-45e6-9266-E9BD0AF00CB7}"), ProgId("C4F.DevKit.PreviewHandler.PreviewHandlers.PdfPreviewHandler"), Guid("574FFFAA-17F6-44b1-A1B4-177AB5900A51"), ClassInterface(ClassInterfaceType.None), ComVisible(True)> _
    Public NotInheritable Class PdfPreviewHandler
        Inherits FileBasedPreviewHandler
        Protected Overrides Function CreatePreviewHandlerControl() As PreviewHandlerControl
            Return New PdfPreviewHandlerControl()
        End Function

        Private NotInheritable Class PdfPreviewHandlerControl
            Inherits FileBasedPreviewHandlerControl
            Public Overrides Sub Load(ByVal file As FileInfo)
                Dim viewer As PdfAxHost = New PdfAxHost()
                Controls.Add(viewer)
                viewer.Dock = DockStyle.Fill

                ' file = MakeTemporaryCopy(file); // to avoid file sharing problems with the PDF control, make a copy first
                viewer.LoadFile(file.FullName)
            End Sub
        End Class

        Private Class PdfAxHost
            Inherits AxHost
            Private _ocx As Object

            Public Sub New()
                MyBase.New("ca8a9780-280d-11cf-a24d-444553540000")
            End Sub

            Protected Overrides Sub AttachInterfaces()
                _ocx = MyBase.GetOcx()
            End Sub

            Public Sub LoadFile(ByVal fileName As String)
                Dim forceCreation As IntPtr = Handle ' necessary for OCX instance to be created
                _ocx.GetType().InvokeMember("LoadFile", BindingFlags.InvokeMethod, Nothing, _ocx, New Object() {fileName}, CultureInfo.InvariantCulture)
            End Sub
        End Class
    End Class
End Namespace